<template>
  <div class="container">
    <div class="header">
      <h2>教师工号管理</h2>
      <div class="actions">
        <el-select
          v-model="selectedDepartment"
          placeholder="选择院系"
          class="department-select"
          clearable
          @change="handleDepartmentChange"
        >
          <el-option v-for="dept in departments" :key="dept" :label="dept" :value="dept" />
        </el-select>
        <el-input
          v-model="searchKeyword"
          placeholder="搜索教师工号/姓名"
          class="search-input"
          @input="searchTeachers"
          clearable
        >
          <template #append>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-button type="primary" @click="showAddDialog">
          <el-icon><Plus /></el-icon> 添加
        </el-button>
        <el-upload
          class="upload-excel"
          :action="uploadUrl"
          :headers="uploadHeaders"
          :data="uploadData"
          :on-progress="handleUploadProgress"
          :on-success="handleImportSuccess"
          :on-error="handleImportError"
          :show-file-list="false"
          accept=".csv"
        >
          <el-button type="success" :loading="uploading">
            <el-icon><Upload /></el-icon> {{ uploading ? `上传中 ${uploadProgress}%` : "导入CSV" }}
          </el-button>
        </el-upload>
        <el-button type="info" @click="downloadTemplate">
          <el-icon><Download /></el-icon> 下载模板
        </el-button>
      </div>
    </div>

    <div class="table-container" ref="tableContainer" @scroll="handleScroll">
      <el-table :data="displayedTeachers" border style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="ID" />
        <el-table-column prop="folder_name" label="院系" />
        <el-table-column prop="user_id" label="工号" />
        <el-table-column prop="cn_name" label="姓名" />
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button size="small" @click="showEditDialog(scope.row)">编辑</el-button>
            <el-popconfirm title="确认删除该教师信息吗？" @confirm="deleteTeacher(scope.row.id)">
              <template #reference>
                <el-button size="small" type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <div v-if="loading" class="loading-more">
        <el-icon class="is-loading"><Loading /></el-icon>
        加载中...
      </div>
      <div v-if="!hasMore && !loading" class="no-more">没有更多数据了</div>
    </div>

    <!-- 添加/编辑教师对话框 -->
    <el-dialog :title="dialogType === 'add' ? '添加教师' : '编辑教师'" v-model="dialogVisible" width="500px">
      <el-form :model="teacherForm" ref="teacherFormRef" :rules="rules" label-width="80px">
        <el-form-item label="院系" prop="folder_name">
          <el-input v-model="teacherForm.folder_name" />
        </el-form-item>
        <el-form-item label="工号" prop="user_id">
          <el-input v-model="teacherForm.user_id" />
        </el-form-item>
        <el-form-item label="姓名" prop="cn_name">
          <el-input v-model="teacherForm.cn_name" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveTeacher">保存</el-button>
      </template>
    </el-dialog>

    <!-- 导入结果对话框 -->
    <el-dialog title="导入结果" v-model="importResultVisible" width="600px">
      <div class="import-result">
        <div class="import-summary">
          <p>总记录数: {{ importResult.total }}</p>
          <p>成功: {{ importResult.success }}</p>
          <p>失败: {{ importResult.failed }}</p>
        </div>
        <template v-if="importResult.errors && importResult.errors.length > 0">
          <h4>错误详情:</h4>
          <el-table :data="importResult.errors" border>
            <el-table-column prop="row" label="行号" width="80" />
            <el-table-column prop="user_id" label="工号" width="120" />
            <el-table-column prop="error" label="错误信息" />
          </el-table>
        </template>
      </div>
      <template #footer>
        <el-button type="primary" @click="importResultVisible = false">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted, reactive, computed } from "vue";
  import { ElMessage } from "element-plus";
  import { Search, Plus, Upload, Download, Loading } from "@element-plus/icons-vue";
  import api from "../axios/api";

  const apiBaseUrl = import.meta.env.VITE_API_BASE_URL;
  const uploadUrl = `${apiBaseUrl}/api/teacher/import_teachers`;
  const uploadHeaders = {
    Authorization: `Bearer ${localStorage.getItem("token")}`
  };

  // 防抖函数
  const debounce = (fn: Function, delay: number) => {
    let timer: ReturnType<typeof setTimeout> | null = null;
    return (...args: any[]) => {
      if (timer) clearTimeout(timer);
      timer = setTimeout(() => {
        fn.apply(null, args);
      }, delay);
    };
  };

  // 上传数据
  const uploadData = computed(() => ({
    user_id: localStorage.getItem("user_id"),
    token: localStorage.getItem("token")
  }));

  // 状态变量
  const loading = ref(false);
  const uploading = ref(false);
  const uploadProgress = ref(0);
  const teachersList = ref<any[]>([]);
  const searchKeyword = ref("");
  const selectedDepartment = ref("");
  const dialogVisible = ref(false);
  const dialogType = ref<"add" | "edit">("add");
  const importResultVisible = ref(false);
  const importResult = ref<any>({});
  const pageSize = ref(30);
  const currentPage = ref(1);
  const hasMore = ref(true);
  const tableContainer = ref<HTMLElement | null>(null);

  // 教师表单
  const teacherFormRef = ref();
  const teacherForm = reactive({
    id: 0,
    folder_name: "",
    user_id: "",
    cn_name: ""
  });

  // 表单验证规则
  const rules = {
    folder_name: [{ required: true, message: "请输入院系名称", trigger: "blur" }],
    user_id: [{ required: true, message: "请输入工号", trigger: "blur" }],
    cn_name: [{ required: true, message: "请输入姓名", trigger: "blur" }]
  };

  // 所有教师数据
  const allTeachers = ref<any[]>([]);

  // 显示的教师数据
  const displayedTeachers = computed(() => {
    return teachersList.value.slice(0, currentPage.value * pageSize.value);
  });

  // 院系列表
  const departments = computed(() => {
    const deptSet = new Set<string>();
    allTeachers.value.forEach(teacher => {
      if (teacher.folder_name) {
        deptSet.add(teacher.folder_name);
      }
    });
    return Array.from(deptSet).sort();
  });

  // 处理院系选择变化
  const handleDepartmentChange = () => {
    searchTeachers();
  };

  // 搜索教师
  const searchTeachers = debounce(() => {
    let filteredTeachers = allTeachers.value;

    // 按院系筛选
    if (selectedDepartment.value) {
      filteredTeachers = filteredTeachers.filter(teacher => teacher.folder_name === selectedDepartment.value);
    }

    // 按关键词搜索
    if (searchKeyword.value.trim()) {
      const keyword = searchKeyword.value.toLowerCase();
      filteredTeachers = filteredTeachers.filter(teacher => {
        return (
          teacher.user_id.toLowerCase().includes(keyword) ||
          teacher.cn_name.toLowerCase().includes(keyword) ||
          teacher.cn_name_initials.toLowerCase().includes(keyword)
        );
      });
    }

    teachersList.value = filteredTeachers;
    currentPage.value = 1;
    hasMore.value = filteredTeachers.length > pageSize.value;
  }, 300);

  // 处理滚动事件
  const handleScroll = (e: Event) => {
    const target = e.target as HTMLElement;
    const { scrollTop, scrollHeight, clientHeight } = target;

    // 当滚动到距离底部20px时触发加载
    if (scrollHeight - scrollTop - clientHeight < 20 && !loading.value && hasMore.value) {
      loadMore();
    }
  };

  // 加载更多数据
  const loadMore = () => {
    if (loading.value || !hasMore.value) return;
    currentPage.value++;
    hasMore.value = teachersList.value.length > currentPage.value * pageSize.value;
  };

  // 获取教师列表
  const fetchTeachers = async () => {
    loading.value = true;
    try {
      const res = await api.getAllTeachers();
      if (res.data) {
        allTeachers.value = res.data;
        teachersList.value = res.data;
        hasMore.value = res.data.length > pageSize.value;
      }
    } catch (err) {
      console.error("获取教师列表失败:", err);
      ElMessage.error("获取教师列表失败");
    } finally {
      loading.value = false;
    }
  };

  // 显示添加对话框
  const showAddDialog = () => {
    dialogType.value = "add";
    resetForm();
    dialogVisible.value = true;
  };

  // 显示编辑对话框
  const showEditDialog = (row: any) => {
    dialogType.value = "edit";
    resetForm();
    Object.assign(teacherForm, row);
    dialogVisible.value = true;
  };

  // 重置表单
  const resetForm = () => {
    teacherForm.id = 0;
    teacherForm.folder_name = "";
    teacherForm.user_id = "";
    teacherForm.cn_name = "";
    if (teacherFormRef.value) {
      teacherFormRef.value.resetFields();
    }
  };

  // 保存教师信息
  const saveTeacher = async () => {
    if (!teacherFormRef.value) return;

    try {
      await teacherFormRef.value.validate();

      if (dialogType.value === "add") {
        await api.addTeacher({
          folder_name: teacherForm.folder_name,
          user_id: teacherForm.user_id,
          cn_name: teacherForm.cn_name
        });
        ElMessage.success("添加教师成功");
      } else {
        await api.updateTeacher({
          id: teacherForm.id,
          folder_name: teacherForm.folder_name,
          user_id: teacherForm.user_id,
          cn_name: teacherForm.cn_name
        });
        ElMessage.success("更新教师成功");
      }

      dialogVisible.value = false;
      fetchTeachers();
    } catch (err: any) {
      if (err.response && err.response.data) {
        ElMessage.error(err.response.data.detail || "操作失败");
      } else {
        ElMessage.error("表单验证失败，请检查输入");
      }
    }
  };

  // 删除教师
  const deleteTeacher = async (id: number) => {
    try {
      await api.deleteTeacher(id);
      ElMessage.success("删除教师成功");
      fetchTeachers();
    } catch (err: any) {
      if (err.response && err.response.data) {
        ElMessage.error(err.response.data.detail || "删除失败");
      } else {
        ElMessage.error("删除失败");
      }
    }
  };

  // 处理上传进度
  const handleUploadProgress = (event: any) => {
    uploading.value = true;
    if (event.percent) {
      uploadProgress.value = Math.floor(event.percent);
    }
  };

  // 处理Excel导入成功
  const handleImportSuccess = (response: any) => {
    uploading.value = false;
    uploadProgress.value = 0;
    importResult.value = response;
    importResultVisible.value = true;
    fetchTeachers();
    ElMessage.success(`导入完成: ${response.success}条记录成功, ${response.failed}条记录失败`);
  };

  // 处理Excel导入失败
  const handleImportError = (error: any) => {
    uploading.value = false;
    uploadProgress.value = 0;
    console.error("导入失败:", error);
    let message = "导入失败";
    if (error.response && error.response.data) {
      message = error.response.data.detail || message;
    }
    ElMessage.error(message);
  };

  // 下载Excel模板
  const downloadTemplate = () => {
    const headers = ["folder_name", "user_id", "cn_name"];
    const csvContent = headers.join(",") + "\n" + "电子信息与控制工程学院,10001,张三\n" + "创意设计学院,10002,李四";

    const blob = new Blob([csvContent], { type: "text/csv;charset=utf-8;" });
    const link = document.createElement("a");
    link.href = URL.createObjectURL(blob);
    link.download = "教师信息导入模板.csv";
    link.click();
    URL.revokeObjectURL(link.href);
  };

  // 初始化加载
  onMounted(() => {
    fetchTeachers();
  });
</script>

<style scoped>
  .container {
    padding: 20px;
  }

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
  }

  .actions {
    display: flex;
    gap: 10px;
  }

  .search-input {
    width: 250px;
  }

  .department-select {
    width: 200px;
  }

  .table-container {
    height: calc(100vh - 200px);
    overflow-y: auto;
    position: relative;
  }

  .loading-more {
    text-align: center;
    padding: 10px;
    color: #909399;
  }

  .no-more {
    text-align: center;
    padding: 10px;
    color: #909399;
  }

  .import-result {
    padding: 10px;
  }

  .import-summary {
    margin-bottom: 15px;
    font-size: 16px;
  }

  .import-summary p {
    margin: 5px 0;
  }
</style>
